<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="充装单位" prop="chargingUnit">
              <el-input v-model="queryParams.chargingUnit" placeholder="请输入充装单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="登记证编号" prop="registrationNumber">
              <el-input v-model="queryParams.registrationNumber" placeholder="请输入登记证编号" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="单位内编号" prop="unitNumber">
              <el-input v-model="queryParams.unitNumber" placeholder="请输入单位内编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="标签号" prop="labelNumber">
              <el-input v-model="queryParams.labelNumber" placeholder="请输入标签号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="二维码号" prop="qrCodeNumber">
              <el-input v-model="queryParams.qrCodeNumber" placeholder="请输入二维码号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="制作单位" prop="manufacturer">
              <el-input v-model="queryParams.manufacturer" placeholder="请输入制作单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="制造日期" prop="manufactureDate">
              <el-date-picker clearable v-model="queryParams.manufactureDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择制造日期" />
            </el-form-item>
            <el-form-item label="检验日期" prop="inspectionDate">
              <el-date-picker clearable v-model="queryParams.inspectionDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择检验日期" />
            </el-form-item>
            <el-form-item label="下次检验日期" prop="nextInspectionDate">
              <el-date-picker clearable v-model="queryParams.nextInspectionDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择下次检验日期" />
            </el-form-item>
            <el-form-item label="钢瓶位置" prop="chargingMedium">
              <el-input v-model="queryParams.chargingMedium" placeholder="请输入钢瓶位置" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="容积" prop="warrantyPeriod">
              <el-input v-model="queryParams.warrantyPeriod" placeholder="请输入容积" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="公称工作压力" prop="nominalPower">
              <el-input v-model="queryParams.nominalPower" placeholder="请输入公称工作压力" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="关联字段" prop="connect">
              <el-input v-model="queryParams.connect" placeholder="请输入关联字段" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['system:DeviceDetail:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:DeviceDetail:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['system:DeviceDetail:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['system:DeviceDetail:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-upload v-model:file-list="fileList" class="upload-demo" :action="requestUploadUrl" :multiple="false"
              :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :limit="1"
              :on-exceed="handleExceed" accept=".xls,.xlsx">
              <el-button type="primary">导入Excel</el-button>
            </el-upload>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="DeviceDetailList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="产品编号" align="center" prop="productNumber" v-if="true" />
        <el-table-column label="充装单位" align="center" prop="chargingUnit" />
        <el-table-column label="登记证编号" align="center" prop="registrationNumber" />
        <el-table-column label="设备品种" align="center" prop="deviceType" />
        <el-table-column label="单位内编号" align="center" prop="unitNumber" />
        <el-table-column label="标签号" align="center" prop="labelNumber" />
        <el-table-column label="二维码号" align="center" prop="qrCodeNumber" />
        <el-table-column label="制作单位" align="center" prop="manufacturer" />
        <el-table-column label="制造日期" align="center" prop="manufactureDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.manufactureDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="检验日期" align="center" prop="inspectionDate" width="80">
          <template #default="scope">
            <span>{{ parseTime(scope.row.inspectionDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="下次检验日期" align="center" prop="nextInspectionDate" width="80">
          <template #default="scope">
            <span>{{ parseTime(scope.row.nextInspectionDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="钢瓶位置" align="center" prop="chargingMedium" />
        <el-table-column label="容积" align="center" prop="warrantyPeriod" />
        <el-table-column label="公称工作压力" align="center" prop="nominalPower" />
        <el-table-column label="状态" align="center" prop="status" />
        <el-table-column label="关联字段" align="center" prop="connect" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:DeviceDetail:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:DeviceDetail:remove']"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.chargingMedium" content="查看位置" placement="top">
              <el-button link type="primary" icon="location" @click="handleweizhi(scope.row)"
                v-hasPermi="['system:DeviceDetail:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改设备详细信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="DeviceDetailFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="充装单位" prop="chargingUnit">
          <el-input v-model="form.chargingUnit" placeholder="请输入充装单位" />
        </el-form-item>
        <el-form-item label="登记证编号" prop="registrationNumber">
          <el-input v-model="form.registrationNumber" placeholder="请输入登记证编号" />
        </el-form-item>
        <el-form-item label="单位内编号" prop="unitNumber">
          <el-input v-model="form.unitNumber" placeholder="请输入单位内编号" />
        </el-form-item>
        <el-form-item label="标签号" prop="labelNumber">
          <el-input v-model="form.labelNumber" placeholder="请输入标签号" />
        </el-form-item>
        <el-form-item label="二维码号" prop="qrCodeNumber">
          <el-input v-model="form.qrCodeNumber" placeholder="请输入二维码号" />
        </el-form-item>
        <el-form-item label="制作单位" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入制作单位" />
        </el-form-item>
        <el-form-item label="制造日期" prop="manufactureDate">
          <el-date-picker clearable v-model="form.manufactureDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择制造日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="检验日期" prop="inspectionDate">
          <el-date-picker clearable v-model="form.inspectionDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择检验日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下次检验日期" prop="nextInspectionDate">
          <el-date-picker clearable v-model="form.nextInspectionDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择下次检验日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="钢瓶位置" prop="chargingMedium">
          <el-input v-model="form.chargingMedium" placeholder="请输入钢瓶位置" />
        </el-form-item>
        <el-form-item label="容积" prop="warrantyPeriod">
          <el-input v-model="form.warrantyPeriod" placeholder="请输入容积" />
        </el-form-item>
        <el-form-item label="公称工作压力" prop="nominalPower">
          <el-input v-model="form.nominalPower" placeholder="请输入公称工作压力" />
        </el-form-item>
        <el-form-item label="关联字段" prop="connect">
          <el-input v-model="form.connect" placeholder="请输入关联字段" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible_1" title="钢瓶位置">
      <div id="map" style="height: 500px;"></div>
      <el-button @click="dialogVisible_1 = false">关闭</el-button>
    </el-dialog>
  </div>
</template>

<script setup name="DeviceDetail" lang="ts">
import { listDeviceDetail, getDeviceDetail, delDeviceDetail, addDeviceDetail, updateDeviceDetail } from '@/api/system/DeviceDetail';
import { DeviceDetailVO, DeviceDetailQuery, DeviceDetailForm } from '@/api/system/DeviceDetail/types';

import AMapLoader from "@amap/amap-jsapi-loader";


import { ElMessage, ElMessageBox } from 'element-plus'


import type { UploadProps, UploadUserFile } from 'element-plus'
import { parseTime } from "../../../utils/ruoyi";


const requestUploadUrl = import.meta.env.VITE_APP_BASE_API + '/system/deviceDetail/uploadExcel'
const fileList = ref<UploadUserFile[]>([
])

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const DeviceDetailList = ref<DeviceDetailVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const DeviceDetailFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogVisible_1 = ref(false);
let map: AMap.Map | null = null;



const initFormData: DeviceDetailForm = {
  productNumber: undefined,
  chargingUnit: undefined,
  registrationNumber: undefined,
  deviceType: undefined,
  unitNumber: undefined,
  labelNumber: undefined,
  qrCodeNumber: undefined,
  manufacturer: undefined,
  manufactureDate: undefined,
  inspectionDate: undefined,
  nextInspectionDate: undefined,
  chargingMedium: undefined,
  warrantyPeriod: undefined,
  nominalPower: undefined,
  status: undefined,
  connect: undefined
}
const data = reactive<PageData<DeviceDetailForm, DeviceDetailQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    chargingUnit: undefined,
    registrationNumber: undefined,
    deviceType: undefined,
    unitNumber: undefined,
    labelNumber: undefined,
    qrCodeNumber: undefined,
    manufacturer: undefined,
    manufactureDate: undefined,
    inspectionDate: undefined,
    nextInspectionDate: undefined,
    chargingMedium: undefined,
    warrantyPeriod: undefined,
    nominalPower: undefined,
    status: undefined,
    connect: undefined,
    params: {
    }
  },
  rules: {
    productNumber: [
      { required: true, message: "产品编号不能为空", trigger: "blur" }
    ],
    chargingUnit: [
      { required: true, message: "充装单位不能为空", trigger: "blur" }
    ],
    registrationNumber: [
      { required: true, message: "登记证编号不能为空", trigger: "blur" }
    ],
    deviceType: [
      { required: true, message: "设备品种不能为空", trigger: "change" }
    ],
    unitNumber: [
      { required: true, message: "单位内编号不能为空", trigger: "blur" }
    ],
    labelNumber: [
      { required: true, message: "标签号不能为空", trigger: "blur" }
    ],
    qrCodeNumber: [
      { required: true, message: "二维码号不能为空", trigger: "blur" }
    ],
    manufacturer: [
      { required: true, message: "制作单位不能为空", trigger: "blur" }
    ],
    manufactureDate: [
      { required: true, message: "制造日期不能为空", trigger: "blur" }
    ],
    inspectionDate: [
      { required: true, message: "检验日期不能为空", trigger: "blur" }
    ],
    nextInspectionDate: [
      { required: true, message: "下次检验日期不能为空", trigger: "blur" }
    ],
    chargingMedium: [
      { required: true, message: "充气介质不能为空", trigger: "blur" }
    ],
    warrantyPeriod: [
      { required: true, message: "容积不能为空", trigger: "blur" }
    ],
    nominalPower: [
      { required: true, message: "公称工作压力不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    connect: [
      { required: true, message: "关联字段不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备详细信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDeviceDetail(queryParams.value);
  DeviceDetailList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  DeviceDetailFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceDetailVO[]) => {
  ids.value = selection.map(item => item.productNumber);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加设备详细信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceDetailVO) => {
  reset();
  const _productNumber = row?.productNumber || ids.value[0]
  const res = await getDeviceDetail(_productNumber);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改设备详细信息";
}

/** 提交按钮 */
const submitForm = () => {
  DeviceDetailFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.productNumber) {
        await updateDeviceDetail(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addDeviceDetail(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: DeviceDetailVO) => {
  const _productNumbers = row?.productNumber || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备详细信息编号为"' + _productNumbers + '"的数据项？').finally(() => loading.value = false);
  await delDeviceDetail(_productNumbers);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

const handleweizhi = (row: DeviceDetailVO) => {
  dialogVisible_1.value = true;
  let x: any = row.chargingMedium.split("-")[0];
  let y: any = row.chargingMedium.split("-")[1];

  x = parseFloat(x) + 0.005519456669247802
  y = parseFloat(y) - 0.002436487435979018

  window._AMapSecurityConfig = {
    securityJsCode: "64a33ad5dbd66ac07be64072d2222f40",
  };

  AMapLoader.load({
    key: "00776650a5ecd2ecc3f8187ac812fbe5", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.ToolBar",
      "AMap.Scale",
      "AMap.HawkEye",
      "AMap.MapType",
      "AMap.Geolocation",
      "AMap.ControlBar",], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then((AMap) => {
      map = new AMap.Map("map", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 15, // 初始化地图级别
        center: [parseFloat(x) + 0.005519456669247802, parseFloat(y) - 0.002436487435979018], // 初始化地图中心点位置
        mapStyle: "amap://styles/whitesmoke" //设置地图的显示样式
      });

      const marker = new AMap.Marker({
        position: new AMap.LngLat(x, y), //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        title: "钢瓶位置"
      });

      map.add(marker);

      AMap.plugin('AMap.Geocoder', function () {
        var geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          city: '010'
        })

        var lnglat = [x, y]

        geocoder.getAddress(lnglat, function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // result为对应的地理位置详细信息
            console.log(result.regeocode.formattedAddress);
            //信息窗体的内容
            var content = [
              "<div><b>"+row.manufacturer +"</b>",
              "下次送检时间 :" + row.nextInspectionDate ,
              "气瓶位置 : "+result.regeocode.formattedAddress+"</div>",
            ];

            //创建 infoWindow 实例
            var infoWindow = new AMap.InfoWindow({
              content: content.join("<br>"), //传入字符串拼接的 DOM 元素
              anchor: "top-left",
            });

            //打开信息窗体
            infoWindow.open(map, [x,y]); //map 为当前地图的实例，map.getCenter() 用于获取地图中心点坐标。

          }
        })
      })
    })
    .catch((e: Error) => {
      console.log(e + 'wee');
    });

}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/DeviceDetail/export', {
    ...queryParams.value
  }, `DeviceDetail_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
